<template>
  <div class="welcome-page">
    <div class="welcome-container">
      <!-- 欢迎标题 -->
      <div class="welcome-header">
        <div class="logo">
          <el-icon size="64" color="#409EFF">
            <Cpu />
          </el-icon>
        </div>
        <h1 class="title">{{ t('welcome.title') }}</h1>
        <p class="subtitle">{{ t('welcome.subtitle') }}</p>
      </div>

      <!-- 主要操作区域 -->
      <div class="welcome-actions">
        <div class="action-cards">
          <!-- 创建新项目 -->
          <div class="action-card" @click="createNewProject">
            <div class="card-icon">
              <el-icon size="48" color="#67C23A">
                <FolderAdd />
              </el-icon>
            </div>
            <h3>{{ t('welcome.createProject.title') }}</h3>
            <p>{{ t('welcome.createProject.description') }}</p>
            <div class="card-actions">
              <el-button type="primary" size="large">
                <el-icon><Plus /></el-icon>
                {{ t('welcome.createProject.button') }}
              </el-button>
            </div>
          </div>

          <!-- 打开现有项目 -->
          <div class="action-card" @click="openExistingProject">
            <div class="card-icon">
              <el-icon size="48" color="#E6A23C">
                <FolderOpened />
              </el-icon>
            </div>
            <h3>{{ t('welcome.openProject.title') }}</h3>
            <p>{{ t('welcome.openProject.description') }}</p>
            <div class="card-actions">
              <el-button type="warning" size="large">
                <el-icon><FolderOpened /></el-icon>
                {{ t('welcome.openProject.button') }}
              </el-button>
            </div>
          </div>
        </div>

        <!-- 最近项目 -->
        <div v-if="recentProjects.length > 0" class="recent-projects">
          <h3>{{ t('welcome.recentProjects') }}</h3>
          <div class="project-list">
            <div
              v-for="project in recentProjects"
              :key="project.id"
              class="project-item"
              @click="openProject(project)"
            >
              <div class="project-icon">
                <el-icon size="24" color="#409EFF">
                  <Folder />
                </el-icon>
              </div>
              <div class="project-info">
                <div class="project-name">{{ project.name }}</div>
                <div class="project-path">{{ project.path }}</div>
                <div class="project-time">{{ project.lastOpenTime }}</div>
              </div>
              <div class="project-actions">
                <el-button
                  text
                  type="danger"
                  @click.stop="deleteProject(project)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部信息 -->
      <div class="welcome-footer">
        <div class="footer-info">
          <p>{{ t('welcome.version') }}</p>
        </div>
      </div>
    </div>

    <!-- 创建项目对话框 -->
    <el-dialog
      v-model="createProjectDialogVisible"
      :title="t('welcome.dialog.createProject.title')"
      width="600px"
      :before-close="handleCreateProjectClose"
    >
      <el-form
        :model="newProjectForm"
        :rules="projectFormRules"
        ref="createProjectFormRef"
        label-width="100px"
      >
        <el-form-item :label="t('welcome.dialog.createProject.name')" prop="name">
          <el-input
            v-model="newProjectForm.name"
            :placeholder="t('welcome.dialog.createProject.namePlaceholder')"
            maxlength="50"
            show-word-limit
            @input="validateProjectName"
          />
          <div v-if="nameValidationMessage" class="validation-message" :class="nameValidationType">
            {{ nameValidationMessage }}
          </div>
        </el-form-item>
        
        <el-form-item :label="t('welcome.dialog.createProject.path')" prop="path">
          <el-input
            v-model="newProjectForm.path"
            :placeholder="t('welcome.dialog.createProject.pathPlaceholder')"
            readonly
          >
            <template #append>
              <el-button @click="selectProjectPath">
                <el-icon><FolderOpened /></el-icon>
                {{ t('welcome.dialog.createProject.selectPath') }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item :label="t('welcome.dialog.createProject.description')">
          <el-input
            v-model="newProjectForm.description"
            type="textarea"
            :rows="3"
            :placeholder="t('welcome.dialog.createProject.descriptionPlaceholder')"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item :label="t('welcome.dialog.createProject.template')">
          <el-radio-group v-model="newProjectForm.template">
            <el-radio label="basic">{{ t('welcome.dialog.createProject.basicTemplate') }}</el-radio>
            <el-radio label="advanced">{{ t('welcome.dialog.createProject.advancedTemplate') }}</el-radio>
            <el-radio label="custom">{{ t('welcome.dialog.createProject.customTemplate') }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCreateProjectClose">{{ t('welcome.dialog.createProject.cancel') }}</el-button>
          <el-button type="primary" @click="handleCreateProjectConfirm" :loading="creating">
            {{ creating ? t('welcome.dialog.createProject.creating') : t('welcome.dialog.createProject.confirm') }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 打开项目对话框 -->
    <el-dialog
      v-model="openProjectDialogVisible"
      :title="t('welcome.dialog.openProject.title')"
      width="500px"
      :before-close="handleOpenProjectClose"
    >
      <div class="open-project-content">
        <p>{{ t('welcome.dialog.openProject.description') }}</p>
        <ul class="required-files">
          <li v-for="(feature, index) in projectFeatures" :key="index">{{ feature }}</li>
        </ul>
        
        <el-form :model="openProjectForm" :rules="openProjectRules" ref="openProjectFormRef">
          <el-form-item :label="t('welcome.dialog.openProject.path')" prop="path">
            <el-input
              v-model="openProjectForm.path"
              :placeholder="t('welcome.dialog.openProject.pathPlaceholder')"
              readonly
            >
              <template #append>
                <el-button @click="selectProjectDirectory">
                  <el-icon><FolderOpened /></el-icon>
                  {{ t('welcome.dialog.openProject.selectDirectory') }}
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleOpenProjectClose">{{ t('welcome.dialog.openProject.cancel') }}</el-button>
          <el-button type="primary" @click="handleOpenProjectConfirm" :loading="opening">
            {{ opening ? t('welcome.dialog.openProject.opening') : t('welcome.dialog.openProject.confirm') }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useI18n } from 'vue-i18n'
import projectService, { type ProjectInfo } from '@/services/projectService'

const { t } = useI18n()

// 使用全局router
const router = getCurrentInstance()?.appContext.config.globalProperties.$router

// 计算属性：项目特性列表
const projectFeatures = computed(() => [
  t('welcome.dialog.openProject.features.0'),
  t('welcome.dialog.openProject.features.1'),
  t('welcome.dialog.openProject.features.2')
])

// 路由导航函数
const navigateTo = (path: string) => {
  if (router) {
    router.push(path)
  }
}

// 最近项目
const recentProjects = ref<ProjectInfo[]>([])

// 创建项目对话框
const createProjectDialogVisible = ref(false)
const creating = ref(false)
const newProjectForm = reactive({
  name: '',
  path: '',
  description: '',
  template: 'basic'
})

// 打开项目对话框
const openProjectDialogVisible = ref(false)
const opening = ref(false)
const openProjectForm = reactive({
  path: ''
})

// 项目名称验证
const nameValidationMessage = ref('')
const nameValidationType = ref('')

// 表单引用
const createProjectFormRef = ref()
const openProjectFormRef = ref()

// 表单验证规则
const projectFormRules = computed(() => ({
  name: [
    { required: true, message: t('welcome.validation.nameRequired'), trigger: 'blur' },
    { min: 1, max: 50, message: t('welcome.validation.nameLength'), trigger: 'blur' }
  ],
  path: [
    { required: true, message: t('welcome.validation.pathRequired'), trigger: 'blur' }
  ]
}))

const openProjectRules = computed(() => ({
  path: [
    { required: true, message: t('welcome.validation.pathRequired'), trigger: 'blur' }
  ]
}))

// 创建新项目
const createNewProject = () => {
  createProjectDialogVisible.value = true
  // 重置表单
  newProjectForm.name = ''
  newProjectForm.path = ''
  newProjectForm.description = ''
  newProjectForm.template = 'basic'
}

// 打开现有项目
const openExistingProject = () => {
  openProjectDialogVisible.value = true
  // 重置表单
  openProjectForm.path = ''
}

// 验证项目名称
const validateProjectName = async () => {
  if (!newProjectForm.name || !newProjectForm.path) {
    nameValidationMessage.value = ''
    return
  }
  
  try {
    // 检查项目是否已存在
    const projects = await projectService.getProjects()
    const fullPath = `${newProjectForm.path}/${newProjectForm.name}`.replace(/\/+/g, '/')
    const existingProject = projects.find(p => p.path === fullPath)
    
    if (existingProject) {
      nameValidationMessage.value = t('welcome.validation.nameExists')
      nameValidationType.value = 'error'
    } else {
      nameValidationMessage.value = t('welcome.validation.nameAvailable')
      nameValidationType.value = 'success'
    }
  } catch (error) {
    nameValidationMessage.value = ''
  }
}

// 选择项目路径
const selectProjectPath = async () => {
  try {
    if ((window as any).electronAPI) {
      const result = await (window as any).electronAPI.selectDirectory()
      
      if (!result.canceled && result.filePaths.length > 0) {
        newProjectForm.path = result.filePaths[0]
        // 重新验证项目名称
        await validateProjectName()
      }
    } else {
      ElMessage.warning(t('welcome.messages.fileSelectionUnavailable'))
    }
  } catch (error) {
    ElMessage.error(t('welcome.messages.selectPathFailed'))
  }
}

// 选择项目目录
const selectProjectDirectory = async () => {
  try {
    if ((window as any).electronAPI) {
      const result = await (window as any).electronAPI.selectDirectory()
      
      if (!result.canceled && result.filePaths.length > 0) {
        openProjectForm.path = result.filePaths[0]
      }
    } else {
      ElMessage.warning(t('welcome.messages.fileSelectionUnavailable'))
    }
  } catch (error) {
    ElMessage.error(t('welcome.messages.selectDirectoryFailed'))
  }
}

// 创建项目确认
const handleCreateProjectConfirm = async () => {
  try {
    await createProjectFormRef.value?.validate()
    
    creating.value = true
    
    // 创建项目
    const project = await projectService.createProject({
      name: newProjectForm.name,
      path: newProjectForm.path,
      description: newProjectForm.description
    })
    
    // 创建项目文件夹结构
    await createProjectStructure({
      ...project,
      template: newProjectForm.template
    })
    
    // 打开项目
    await projectService.openProject(project.path)
    
    ElMessage.success({
      message: t('welcome.messages.projectCreated'),
      duration: 3000
    })
    handleCreateProjectClose()
    
    // 跳转到IDE
    navigateTo('/ide')
    
  } catch (error) {
    const errorMessage = (error as Error).message || t('welcome.messages.createFailed')
    console.error('创建项目失败:', error)
    
    // 根据错误类型显示不同的提示
    if (errorMessage.includes('项目已存在')) {
      ElMessage.error(t('welcome.messages.projectExists'))
    } else if (errorMessage.includes('目录已存在')) {
      ElMessage.error(t('welcome.messages.directoryExists'))
    } else {
      ElMessage.error(errorMessage)
    }
  } finally {
    creating.value = false
  }
}

// 打开项目确认
const handleOpenProjectConfirm = async () => {
  try {
    await openProjectFormRef.value?.validate()
    
    opening.value = true
    
    // 项目路径验证（基本检查）
    if (!openProjectForm.path || openProjectForm.path.trim() === '') {
      throw new Error(t('welcome.validation.pathRequired'))
    }
    
    // 打开项目
    await projectService.openProject(openProjectForm.path)
    
    ElMessage.success({
      message: t('welcome.messages.projectOpened'),
      duration: 3000
    })
    handleOpenProjectClose()
    
    // 跳转到IDE
    navigateTo('/ide')
    
  } catch (error) {
    ElMessage.error((error as Error).message || t('welcome.messages.openFailed'))
  } finally {
    opening.value = false
  }
}

// 打开项目
const openProject = async (project: ProjectInfo) => {
  try {
    await projectService.openProject(project.path)
    ElMessage.success({
      message: `${t('welcome.messages.projectOpened')}: ${project.name}`,
      duration: 3000
    })
    navigateTo('/ide')
  } catch (error) {
    ElMessage.error((error as Error).message || t('welcome.messages.openFailed'))
  }
}

// 删除项目
const deleteProject = async (project: ProjectInfo) => {
  try {
    await ElMessageBox.confirm(
      t('welcome.confirm.deleteProject', { name: project.name }),
      t('welcome.confirm.deleteTitle'),
      {
        type: 'warning'
      }
    )
    
    await projectService.deleteProject(project.id)
    await loadRecentProjects()
    
    ElMessage.success({
      message: t('welcome.messages.projectDeleted'),
      duration: 3000
    })
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(t('welcome.messages.deleteFailed'))
    }
  }
}

// 创建项目结构
const createProjectStructure = async (projectData: any) => {
  try {
    if ((window as any).electronAPI) {
      ElMessage.info(t('welcome.messages.creatingStructure'))
      
      const result = await (window as any).electronAPI.createProjectStructure({
        name: projectData.name,
        path: newProjectForm.path, // 使用原始路径，不包含项目名称
        template: projectData.template
      })
      
      if (result.success) {
        ElMessage.success({
          message: t('welcome.messages.structureCreated'),
          duration: 3000
        })
        return result.projectPath
      } else {
        throw new Error(result.error || t('welcome.messages.structureCreateFailed'))
      }
    } else {
      throw new Error(t('welcome.messages.projectCreateUnavailable'))
    }
  } catch (error) {
    throw new Error(`${t('welcome.messages.structureCreateFailed')}: ${(error as Error).message}`)
  }
}

// 关闭创建项目对话框
const handleCreateProjectClose = () => {
  createProjectDialogVisible.value = false
  createProjectFormRef.value?.resetFields()
  // 重置验证状态
  nameValidationMessage.value = ''
  nameValidationType.value = ''
}

// 关闭打开项目对话框
const handleOpenProjectClose = () => {
  openProjectDialogVisible.value = false
  openProjectFormRef.value?.resetFields()
}


// 加载最近项目
const loadRecentProjects = async () => {
  try {
    recentProjects.value = await projectService.getRecentProjects(5)
  } catch (error) {
    console.error('加载最近项目失败:', error)
  }
}

// 生命周期
onMounted(() => {
  loadRecentProjects()
})
</script>

<style scoped>
.welcome-page {
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.welcome-container {
  background: white;
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  padding: 40px;
  max-width: 800px;
  width: 100%;
  max-height: 90vh;
  overflow-y: auto;
}

.welcome-header {
  text-align: center;
  margin-bottom: 40px;
}

.logo {
  margin-bottom: 20px;
}

.title {
  font-size: 32px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 10px 0;
}

.subtitle {
  font-size: 16px;
  color: #7f8c8d;
  margin: 0;
}

.welcome-actions {
  margin-bottom: 40px;
}

.action-cards {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 30px;
  margin-bottom: 40px;
}

.action-card {
  background: #f8f9fa;
  border: 2px solid #e9ecef;
  border-radius: 12px;
  padding: 30px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.action-card:hover {
  border-color: #409EFF;
  box-shadow: 0 8px 25px rgba(64, 158, 255, 0.15);
  transform: translateY(-2px);
}

.card-icon {
  margin-bottom: 20px;
}

.action-card h3 {
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 10px 0;
}

.action-card p {
  font-size: 14px;
  color: #7f8c8d;
  margin: 0 0 20px 0;
  line-height: 1.5;
}

.card-actions {
  margin-top: 20px;
}

.recent-projects {
  margin-top: 30px;
}

.recent-projects h3 {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 20px 0;
}

.project-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.project-item {
  display: flex;
  align-items: center;
  padding: 16px;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.project-item:hover {
  background: #e3f2fd;
  border-color: #409EFF;
}

.project-icon {
  margin-right: 16px;
}

.project-info {
  flex: 1;
}

.project-name {
  font-size: 16px;
  font-weight: 500;
  color: #2c3e50;
  margin-bottom: 4px;
}

.project-path {
  font-size: 12px;
  color: #7f8c8d;
  margin-bottom: 2px;
}

.project-time {
  font-size: 11px;
  color: #95a5a6;
}

.project-actions {
  margin-left: 16px;
}

.welcome-footer {
  border-top: 1px solid #e9ecef;
  padding-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.footer-links {
  display: flex;
  gap: 16px;
}

.footer-info {
  font-size: 12px;
  color: #7f8c8d;
}

.open-project-content {
  margin-bottom: 20px;
}

.required-files {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  padding: 16px;
  margin: 16px 0;
}

.required-files li {
  margin-bottom: 8px;
  font-size: 14px;
  color: #495057;
}

.required-files code {
  background: #e9ecef;
  padding: 2px 6px;
  border-radius: 3px;
  font-family: 'Consolas', 'Monaco', monospace;
  font-size: 12px;
}

.validation-message {
  font-size: 12px;
  margin-top: 4px;
  padding: 4px 8px;
  border-radius: 4px;
}

.validation-message.success {
  color: #67c23a;
  background: #f0f9ff;
  border: 1px solid #b3e19d;
}

.validation-message.error {
  color: #f56c6c;
  background: #fef0f0;
  border: 1px solid #fbc4c4;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .welcome-container {
    padding: 20px;
    margin: 10px;
  }
  
  .action-cards {
    grid-template-columns: 1fr;
    gap: 20px;
  }
  
  .action-card {
    padding: 20px;
  }
  
  .title {
    font-size: 24px;
  }
  
  .welcome-footer {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }
}

@media (max-width: 480px) {
  .welcome-page {
    padding: 10px;
  }
  
  .welcome-container {
    padding: 16px;
  }
  
  .title {
    font-size: 20px;
  }
  
  .subtitle {
    font-size: 14px;
  }
}
</style>
